package fi.profecons.csswindows.toolkit;

import org.apache.commons.lang.StringEscapeUtils;

import fi.profecons.csswindows.ActionListener;
import fi.profecons.csswindows.Element;

public class Console extends Frame implements ActionListener {

	private Input input;

	private Textarea output;

	private int bufferSize = 100;

	private String[] buffer = new String[bufferSize];

	private int lineNumber = 0;

	public Console() {
		super();
		setSize(655, 480);
		input = new Input();
		input.setBounds(10, 370, 620, 20);
		input.setActionListener(this);
		output = new Textarea();
		output.setBounds(10, 10, 620, 350);
		output.disable();
		add(input);
		add(output);
	}

	public void println(String s) {
		int counter = lineNumber % bufferSize;
		StringBuffer sb = new StringBuffer();
		buffer[counter] = StringEscapeUtils.escapeJavaScript(s);
		for (int i = 0; i < bufferSize; i++) {
			if (buffer[(counter + i + 1) % bufferSize] != null) {
				sb.append(buffer[(counter + i + 1) % bufferSize]);
				sb.append("\\r\\n");
				
			}
		}
		lineNumber++;
		output.setValue(sb.toString());
	}

	public void handleAction(Element e, String action) {
		if (action.equals("enter")) {
			Input i = (Input) e;
			addCommand(i.getValue());
			println(i.getValue());
			input.setValue("");
		}
	}

	public Input getInput() {
		return input;
	}

	public void setInput(Input input) {
		this.input = input;
	}

	public Textarea getOutput() {
		return output;
	}

	public void setOutput(Textarea output) {
		this.output = output;
	}

	public int getBufferSize() {
		return bufferSize;
	}

	public void setBufferSize(int bufferSize) {
		this.bufferSize = bufferSize;
		this.buffer = new String[bufferSize];
	}

}
